package com.hw.config.shiro.jwt;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.hw.common.ResponseCode;
import com.hw.model.ResponseResult;
import com.hw.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * <p>JWT过滤器
 * <p>先检查请求头中是否包含JWT token，若不包含直接拒绝访问。
 * <p>反之，jwtFilter会将请求头中包含的JWT token封装成JwtToken对象，并调用subject.login(token)方法交给Shiro去进行登录判断。
 * <p>执行顺序：preHandle->isAccessAllowed->isLoginAttempt->executeLogin
 *
 * @author whw
 * @date 2021/6/11
 */
@Slf4j
public class JwtFilter extends BasicHttpAuthenticationFilter {
    /**
     * 前置处理
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
        HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }

    /**
     * 后置处理
     *
     * @param request
     * @param response
     */
    @Override
    protected void postHandle(ServletRequest request, ServletResponse response) {
        // 添加跨域支持
        this.fillCorsHeader(WebUtils.toHttp(request), WebUtils.toHttp(response));
    }

    /**
     * 添加跨域支持
     *
     * @param httpServletRequest
     * @param httpServletResponse
     */
    protected void fillCorsHeader(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,HEAD");
        httpServletResponse.setHeader("Access-Control-Allow-Headers",
                httpServletRequest.getHeader("Access-Control-Request-Headers"));
    }

    /**
     * 过滤器拦截请求的入口方法，如果带有token，则对token进行检查，否则直接通过
     *
     * @param request
     * @param response
     * @param mappedValue
     * @return true:允许访问，false:禁止访问，会进入{@link #onAccessDenied(ServletRequest, ServletResponse)} )}
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        // 判断请求的请求头是否带上 "Token"
        if (isLoginAttempt(request, response)) {
            try {
                // 如果存在，则进入 executeLogin 方法执行登入，检查 token 是否正确
                executeLogin(request, response);
                return true;
            } catch (Exception e) {
                // 认证出现异常，传递错误信息msg
                String message = e.getMessage();
                // 获取应用异常(该Cause是导致抛出此throwable(异常)的throwable(异常))
                Throwable throwable = e.getCause();
                if (throwable instanceof TokenExpiredException) {
                    message = "token已过期";
                } else if (throwable instanceof JWTVerificationException) {
                    message = "token校验失败";
                } else {
                    if (throwable != null) {
                        message = throwable.getMessage();
                    }
                }

                responseError(response, message);
                return false;
            }
        } else {
            // 没有携带Token
            HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
            // 获取当前请求类型
            String httpMethod = httpServletRequest.getMethod();
            // 获取当前请求URI
            String uri = httpServletRequest.getRequestURI();
            log.info("当前请求token为空:[{}] {}", httpMethod, uri);
            responseError(response, ResponseCode.MISSING_TOKEN.getCode(), ResponseCode.MISSING_TOKEN.getMsg());
            return false;
        }
    }

    /**
     * 检查Header里面是否包含Token字段，有就进行Token登录认证授权
     *
     * @param request
     * @param response
     * @return
     */
    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        return ((HttpServletRequest) request).getHeader(JwtUtils.tokenAuthHeader) != null;
    }

    /**
     * 身份验证,检查JWT token是否合法
     *
     * @param request
     * @param response
     * @return
     */
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String token = httpServletRequest.getHeader(JwtUtils.tokenAuthHeader);
        JwtToken jwtToken = new JwtToken(token);
        // 交给 Shiro 去进行登录验证
        getSubject(request, response).login(jwtToken);
        // 如果没有抛出异常则代表登入成功，返回true
        return true;
    }

    /**
     * 重写 onAccessDenied 方法，避免父类中调用再次executeLogin；
     * {@link #isAccessAllowed(ServletRequest, ServletResponse, Object)}方法返回false，会进入该方法，表示拒绝访问
     *
     * @param servletRequest
     * @param servletResponse
     * @return
     */
    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) {
        // 加上下面这句，进入swagger会一直弹出身份校验。暂时不清楚原因，先注释掉
        // this.sendChallenge(servletRequest, servletResponse);
        return false;
    }

    /**
     * 响应错误信息
     *
     * @param response
     * @param message  响应消息
     */
    private void responseError(ServletResponse response, String message) {
        try {
            HttpServletResponse httpResponse = WebUtils.toHttp(response);
            httpResponse.setCharacterEncoding("UTF-8");
            httpResponse.setContentType("application/json;charset=UTF-8");
            httpResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
            PrintWriter writer = httpResponse.getWriter();
            ResponseResult<?> result = ResponseResult.error(ResponseCode.UNAUTHORIZED.getCode(), message);
            writer.write(JSONObject.toJSONString(result));
        } catch (IOException e) {
            log.error("返回Response信息出现IOException异常:" + e.getMessage(), e);
        }
    }

    /**
     * 响应错误信息
     *
     * @param response
     * @param code     响应码
     * @param message  响应消息
     */
    private void responseError(ServletResponse response, int code, String message) {
        try {
            HttpServletResponse httpResponse = WebUtils.toHttp(response);
            httpResponse.setCharacterEncoding("UTF-8");
            httpResponse.setContentType("application/json;charset=UTF-8");
            httpResponse.setStatus(code);
            PrintWriter writer = httpResponse.getWriter();
            ResponseResult<?> result = ResponseResult.error(code, message);
            writer.write(JSONObject.toJSON(result).toString());
        } catch (IOException e) {
            log.error("返回Response信息出现IOException异常:" + e.getMessage(), e);
        }
    }
}
